<template>
  <div>
    <div>
      <h1>商品列表</h1>
    </div>
    <div>
      <el-button type="primary" @click="handleAddProd">添加商品</el-button>
      <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
    </div>

    <div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="prodId" label="商品ID" />
        <el-table-column prop="prodSpu" label="商品SPU" />
        <el-table-column prop="prodName" label="商品名称" />
        <el-table-column prop="typeName" label="商品类型"> </el-table-column>
        <el-table-column prop="brandName" label="品牌" />
        <el-table-column prop="unitName" label="单位" />
        <el-table-column prop="tagName" label="标签" />
        <el-table-column prop="apprName" label="供应商" />
        <el-table-column prop="prodImage" label="图片">
          <template #default="scope">
            <el-image
              :src="scope.row.prodImage"
              style="width: 50px; height: 50px"
              v-if="scope.row.prodImage != null"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="prodStatus" label="状态">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.prodStatus == 0"
              >上架</el-tag
            >
            <el-tag v-if="scope.row.prodStatus == 1">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dictLabel" label="种类"> </el-table-column>
        <el-table-column prop="createTime" label="时间" />
        <el-table-column label="操作"></el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div style="margin-top: 20px">
      <div class="demo-pagination-block" style="width: 800px; margin: 0 auto">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加商品 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="商品添加" width="500">
        <el-form :model="form">
          <el-form-item label="商品类型:" :label-width="formLabelWidth">
            <el-radio-group v-model="form.kindId">
              <el-radio :value="0">实物商品</el-radio>
              <el-radio :value="1">虚拟商品</el-radio>
              <el-radio :value="2">卡密/网盘</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品分类:" :label-width="formLabelWidth">
            <el-tree-select
              v-model="form.typeId"
              :data="typeListTree"
              check-strictly
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="商品名称:" :label-width="formLabelWidth">
            <el-input v-model="form.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商品SPU:" :label-width="formLabelWidth">
            <el-input v-model="form.prodSpu" autocomplete="off" />
          </el-form-item>

          <el-form-item label="商品品牌:" :label-width="formLabelWidth">
            <el-select v-model="form.brandId" placeholder="请选择商品品牌">
              <el-option
                v-for="item in brandListAll"
                :label="item.brandName"
                :value="item.brandId"
                :key="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品单位:" :label-width="formLabelWidth">
            <el-select v-model="form.unitId" placeholder="请选择商品单位">
              <el-option
                v-for="item in unitListAll"
                :label="item.unitName"
                :value="item.unitId"
                :key="item.unitId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品标签:" :label-width="formLabelWidth">
            <el-select v-model="form.tagId" placeholder="请选择商品标签">
              <el-option
                v-for="item in tagListAll"
                :label="item.tagName"
                :value="item.tagId"
                :key="item.tagId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商:" :label-width="formLabelWidth">
            <el-select v-model="form.apprId" placeholder="请选择供应商">
              <el-option
                v-for="item in apprListAll"
                :label="item.apprName"
                :value="item.apprId"
                :key="item.apprId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品缩略图:" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/shop/type/uploadFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">放弃</el-button>
            <el-button type="primary" @click="onSubmitAddProd">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import {
  getProdList,
  addProd,
  getTypeSelectTree,
  getBrandListAll,
  getTagList,
  getUnitList,
  getApprList,
  deleteAllProd,
} from "@/api/api";
import { ElMessage, ElMessageBox } from "element-plus";
const dialogFormVisible = ref(false);
const multipleSelection = ref<any[]>([]);
const formLabelWidth = "140px";
const tableData = ref();
const total = ref(0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
});
const form = ref({
  apprId: null,
  brandId: null,
  createBy: null,
  createTime: null,
  kindId: null,
  prodId: null,
  prodImage: null,
  prodName: null,
  prodSpu: null,
  prodStatus: null,
  tagId: null,
  typeId: null,
  unitId: null,
  updateBy: null,
  updateTime: null,
});
const typeListTree = ref([]);
const brandListAll = ref([]);
const tagListAll = ref([]);
const unitListAll = ref([]);
const apprListAll = ref([]);

const resetForm = () => {
  form.value = {
    apprId: null,
    brandId: null,
    createBy: null,
    createTime: null,
    kindId: null,
    prodId: null,
    prodImage: null,
    prodName: null,
    prodSpu: null,
    prodStatus: null,
    tagId: null,
    typeId: null,
    unitId: null,
    updateBy: null,
    updateTime: null,
  };
  imageUrl.value = "";
};

//批量删除
const handleDeleteAll = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择需要删除的商品");
    return;
  }
  ElMessageBox.confirm("数据删除后无法恢复,您确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteAllProd(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("批量删除成功");
          loadProdList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};

//多选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

//提交添加商品
const onSubmitAddProd = () => {
  form.value.prodImage = imageUrl.value;
  addProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      loadProdList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//图片成功回调函数
const imageUrl = ref("");
const headers = {
  token: sessionStorage.getItem("token") || "",
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};

//添加商品
const handleAddProd = () => {
  resetForm();
  dialogFormVisible.value = true;
};

//分页改变函数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadProdList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadProdList();
};

//商品列表
const loadProdList = () => {
  getProdList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      total.value = res.data.data.total;
      tableData.value = res.data.data.records;
    }
  });
};

//页面加载钩子函数
onMounted(() => {
  loadProdList();
  //获取商品类型树
  getTypeSelectTree().then((res) => {
    if (res.data.code == 200) {
      typeListTree.value = res.data.data;
    }
  });
  //获取商品品牌
  getBrandListAll().then((res) => {
    if (res.data.code == 200) {
      brandListAll.value = res.data.data;
    }
  });
  //获取所有商品标签
  getTagList().then((res) => {
    if (res.data.code == 200) {
      tagListAll.value = res.data.data;
    }
  });
  //获取所有商品单位
  getUnitList().then((res) => {
    if (res.data.code == 200) {
      unitListAll.value = res.data.data;
    }
  });
  //获取所有供应商
  getApprList().then((res) => {
    if (res.data.code == 200) {
      apprListAll.value = res.data.data;
    }
  });
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
